package servlet;

import java.io.IOException;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.Appointment;
import entity.User;
import session.AppointmentDao;

/**
 * Kontroller za dodavanje novog termina
 * 
 * @author rigo & jung
 *
 */
public class AddAppointment extends HttpServlet {
	private static final long serialVersionUID = -7590565944785626120L;
	
	@EJB
	protected AppointmentDao appointmentDao ;
	 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			User admin;
			if((admin = (User)request.getSession().getAttribute("user"))==null ||
					admin.getType()!='A'){
				response.sendRedirect(response.encodeURL("./login.jsp"));
				return;
			}

			String location = null;
			Date date = null;
			Time from = null;
			Time to = null;
			
			DateFormat df = new SimpleDateFormat("dd.MM.yyyy");

			if(request.getParameter("location")!=null && !request.getParameter("location").equals(""))
				location = request.getParameter("location");
			if(request.getParameter("date")!=null && !request.getParameter("date").equals(""))
				date = df.parse((request.getParameter("date")));
			if(request.getParameter("from")!=null && !request.getParameter("from").equals(""))
				from = Time.valueOf((request.getParameter("from")+":00"));
			if(request.getParameter("to")!=null && !request.getParameter("to").equals(""))
				to = Time.valueOf((request.getParameter("to")+":00"));
			if(appointmentDao.checkAppointment(date, from, to)){
				Appointment app = new Appointment();
				app.setLocation(location);
				app.setDate(date);
				app.setFrom(from);
				app.setTo(to);
				app.setExpired(false);
				app.setDeleted(false);
				appointmentDao.persist(app);
			}else{
				request.setAttribute("message", "Uneli ste termin koji se preklapa sa nekom drugom!");
				getServletContext().getRequestDispatcher("/addAppointment.jsp").forward(request, response);
				return;
			}
			response.sendRedirect(response.encodeURL("./ListAppointments"));
		}catch (ParseException e){
			request.setAttribute("message", "Pogrešno unet datum ili vreme!");
			getServletContext().getRequestDispatcher("/addAppointment.jsp").forward(request, response);
			return;
		}catch (Exception e) {

		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
